package de.gwtprime.client.widgets;

import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.PrimeRequestFactory;
import de.gwtprime.client.event.QuestionAddedEvent;
import de.gwtprime.client.event.QuestionOnTypeEvent;
import de.gwtprime.client.util.AppUtils;
import de.gwtprime.client.util.HasTextTitleAndProxy;
import de.gwtprime.client.widgets.util.UploadWidget;
import de.gwtprime.shared.requestFactory.ArticleSectionProxy;
import de.gwtprime.shared.requestFactory.QuestionProxy;
import de.gwtprime.shared.requestFactory.request.ArticleSectionRequest;
import de.gwtprime.shared.requestFactory.request.QuestionRequest;

public class AddQuestionWidget extends Composite implements HasTextTitleAndProxy{

	interface AddQuestionWiddgetUiBinder extends UiBinder<Widget, AddQuestionWidget>{}
	AddQuestionWiddgetUiBinder uiBinder = GWT.create(AddQuestionWiddgetUiBinder.class);

	@UiField TextBox questionTitle;
	@UiField TextArea questionText;
	@UiField Button addQuestionBtn;
	boolean newQuestion = false;
	private final ClientFactory clientFactory;
	private final ArticleSectionProxy articleSection;
	private QuestionProxy question;
	
	@UiField SimplePanel uploadWidget;
	
	public AddQuestionWidget(final ArticleSectionProxy articleSection, final ClientFactory clientFactory){
		this(null, articleSection, clientFactory);
		newQuestion=true;
		
	}
	
	public AddQuestionWidget(final QuestionProxy question, final ArticleSectionProxy articleSection, final ClientFactory clientFactory){
		initWidget(uiBinder.createAndBindUi(this));

		this.question = question;
		this.clientFactory = clientFactory;
		this.articleSection = articleSection;
		
		
		if(question!=null){
			questionText.setText(question.getText());
			questionTitle.setText(question.getTitle());
		}
		
		questionText.addKeyUpHandler(new QuestionChangeHandler());
		questionText.getElement().setAttribute("placeholder", "Enter your question here");
		questionTitle.addKeyUpHandler(new QuestionChangeHandler());
		questionTitle.getElement().setAttribute("placeholder", "Enter a title for your question");
		addQuestionBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				
				if (!newQuestion) {
					updateExistingQuestion(clientFactory, question);
				} else {
					createNewQuestion(clientFactory, articleSection, question);
				}
				questionTitle.setText("");
				questionText.setText("");
			
			}
		});
		
		uploadWidget.add(new UploadWidget(clientFactory, this));
		
	}
	
	
	public void updateExistingQuestion(ClientFactory clientFactory, QuestionProxy question){

		// clear the comments and sections because they cause a lot of lookups
		// TODO better solution?
		question.getAnswers().clear();
		
		final PrimeRequestFactory requestFactory = clientFactory.getRequestFactory();
		final QuestionRequest request = requestFactory.questionRequest();
		QuestionProxy qustionProxy = request.edit(question);
		qustionProxy.setText(questionText.getText());
		qustionProxy.setTitle(questionTitle.getText());

		Request<Long> createReq2 = request.persist().using(qustionProxy);

		createReq2.fire(new Receiver<Long>() {
			@Override
			public void onSuccess(Long list) {
				setVisible(false);// TODO
			}

			@Override
			public void onFailure(ServerFailure error) {
				System.out.println("failed"); // TODO
			}
		});
	}
	
	public void createNewQuestion(final ClientFactory clientFactory, ArticleSectionProxy articleSection, QuestionProxy question){
		
		final PrimeRequestFactory requestFactory = clientFactory.getRequestFactory();
		final ArticleSectionRequest articleSectionRequest = requestFactory.articleSectionRequest();
		
		final QuestionProxy newQuestion = articleSectionRequest.create(QuestionProxy.class);
		
		newQuestion.setUser(clientFactory.getUser());
		
		newQuestion.setText(questionText.getText());
		newQuestion.setTitle(questionTitle.getText());

		Request<QuestionProxy> createReq2 = articleSectionRequest.addQuestion(newQuestion).using(articleSection);
		
		createReq2.fire(new Receiver<QuestionProxy>() {
			@Override
			public void onSuccess(QuestionProxy question) {
				clientFactory.getEventBus().fireEvent(new QuestionAddedEvent(question));
			}

			@Override
			public void onFailure(ServerFailure error) {
				System.out.println("failed"); // TODO
			}
		});
		
	}
		
	class QuestionChangeHandler implements KeyUpHandler{

		@Override
		public void onKeyUp(KeyUpEvent event) {
			
			clientFactory.getEventBus().fireEvent(new QuestionOnTypeEvent(
							question == null ? null : question.getId(), 
							questionTitle.getText(), 
							questionText.getText(), 
							question == null ? "" : question.getImages()));			
		}
	}

	@Override
	public String getText() {
		return questionText.getText();
	}

	@Override
	public void setText(String text) {
		questionText.setText(AppUtils.editForClient(text));
		
	}

	@Override
	public String getTitleString() {
		return questionTitle.getText();
	}

	@Override
	public <T extends EntityProxy> void setProxy(T entity) {
		question = (QuestionProxy)entity;
		
	}

	@Override
	public <T extends EntityProxy> T getProxy() {
		return (T) question;
	}

	@Override
	public void setImages(final String images) {
		QuestionRequest request = clientFactory.getRequestFactory().questionRequest();
		
		if(question == null){
			
			QuestionProxy question = request.create(QuestionProxy.class);
			question.setImages(images);
			request.persist().using(question).fire();
			this.question = question;
			return;
		}
		
		
		request.findQuestion(question.getId()).fire(new Receiver<QuestionProxy>() {

			@Override
			public void onSuccess(QuestionProxy response) {
				QuestionRequest request = clientFactory.getRequestFactory().questionRequest();
				response = request.edit(response);
				response.setImages(images);
				request.persist().using(response).fire();
				
				question = response;
				
			}
		});
		
	}

	@Override
	public String getImages() {
		if(question==null)
			return "";
		return question.getImages();
	}

	@Override
	public void updateTextAndImages(String images, String text) {
		setText(text);
		clientFactory.getEventBus().fireEvent(new QuestionOnTypeEvent(question == null ? null : question.getId(), getTitleString(), text, images));	
	}
}

